package com.sh.utils.Http;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.qiniu.android.utils.StringUtils;
import com.squareup.okhttp.*;
import lombok.Data;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Data
public class OkHttpUtils {
    private static final String TAG = "OKHttpUtils";
    private static OkHttpUtils instance;
    private OkHttpClient client;
    private Handler handler;

    private OkHttpUtils() {
        this.client = new OkHttpClient();
        //设置连接超时时间
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        //设置响应超时时间
        client.setWriteTimeout(10, TimeUnit.SECONDS);
        //请求的超时时间
        client.setReadTimeout(30, TimeUnit.SECONDS);
        //允许使用Cookie
        client.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
        //获取主线程的handler
        handler = new Handler(Looper.getMainLooper());
    }

    public static OkHttpUtils getInstance() {
        if (instance == null) {
            //加同步安全
            synchronized (OkHttpUtils.class) {
                if (instance == null) {
                    instance = new OkHttpUtils();
                }
            }
        }
        return instance;
    }

    /**
     * 构造Get请求
     *
     * @param url      请求的url
     * @param callback 结果回调的方法
     */
    private void getRequest(String url, final ResultCallback callback) {
        final Request request = new Request.Builder().url(url).build();
        deliveryResult(callback, request);
    }

    /**
     * 构造post 请求
     *
     * @param url      请求的url
     * @param callback 结果回调的方法
     * @param params   请求参数
     */
    private void postRequest(String url, final ResultCallback callback, List<Param> params) {
        Request request = buildPostRequest(url, params);
        deliveryResult(callback, request);
    }

    /**
     * 同步请求返回字符串
     *
     * @param request
     * @return
     * @throws IOException
     */
    private String syncDeliverResultForString(Request request) throws IOException {
        String resStr = null;
        Call postCall = getClient().newCall(request);
        Response response = postCall.execute();
        //响应成功
        if (response.isSuccessful()) {
            resStr = response.body().string();
        }
        return resStr;
    }

    /**
     * 同步请求返回Map
     *
     * @param request
     * @return
     * @throws IOException
     */
    private Map<String, String> syncDeliverResultForMap(Request request) throws IOException {
        Map<String, String> resMap = null;
        Call postCall = getClient().newCall(request);
        Response response = postCall.execute();
        //响应成功
        if (response.isSuccessful()) {
            String string = response.body().string();
            if (!StringUtils.isNullOrEmpty(string)) {
                try {
                    resMap = new Gson().fromJson(string, Map.class);
                } catch (Exception e) {
                    throw e;
                }
            }
        }
        return resMap;
    }

    /**
     * 处理请求结果的回调
     *
     * @param callback
     * @param request
     */
    private void deliveryResult(final ResultCallback callback, Request request) {

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, final IOException e) {
                //Log.i("请求结果 ","失败");
                sendFailCallback(callback, e);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // Log.i("请求结果 ","成功");
                try {
                    String str = response.body().string();
                    if (callback.mType == String.class) {
                        sendSuccessCallBack(callback, str);
                    } else {
                        Object object = new Gson().fromJson(str, callback.mType);
                        sendSuccessCallBack(callback, object);
                    }
                } catch (final Exception e) {
                    Log.e("error", "convert json failure", e);
                    sendFailCallback(callback, e);
                }

            }
        });
    }

    /**
     * 发送失败的回调
     *
     * @param callback
     * @param e
     */
    private void sendFailCallback(final ResultCallback callback, final Exception e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }
        });
    }

    /**
     * 发送成功的调
     *
     * @param callback
     * @param obj
     */
    private void sendSuccessCallBack(final ResultCallback callback, final Object obj) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    callback.onSuccess(obj);
                }
            }
        });
    }

    /**
     * 构造post请求
     *
     * @param url    请求url
     * @param params 请求的参数
     * @return 返回 Request
     */
    private Request buildPostRequest(String url, List<Param> params) {
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Param param : params) {
            builder.add(param.key, param.value);
        }
        RequestBody requestBody = builder.build();
        return new Request.Builder().url(url).post(requestBody).build();
    }


    /**********************对外接口************************/

    /**
     * get请求
     *
     * @param url      请求url
     * @param callback 请求回调
     */
    public static void get(String url, ResultCallback callback) {
        getInstance().getRequest(url, callback);
    }

    /**
     * post请求
     *
     * @param url      请求url
     * @param callback 请求回调
     * @param params   请求参数
     */
    public static void post(String url, final ResultCallback callback, List<Param> params) {
        getInstance().postRequest(url, callback, params);
    }

    /**
     * 同步post请求返回String
     * @param url
     * @param params
     * @return
     */
    public static String syncPostForString(String url,List<Param> params){
        String res = null;
        Request request = getInstance().buildPostRequest(url,params);
        try {
            res = getInstance().syncDeliverResultForString(request);
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
        }
        return res;
    }

    /**
     * 同步post请求返回Map
     * @param url
     * @param params
     * @return
     */
    public static Map<String,String> syncPostForMap(String url,List<Param> params){
        Map<String,String> resMap = null;
        Request request = getInstance().buildPostRequest(url,params);
        try {
            resMap = getInstance().syncDeliverResultForMap(request);
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
        }
        return resMap;
    }

    /**
     * 同步get请求返回String
     * @param url
     * @return
     */
    public static String syncGetForString(String url){
        String res = null;
        Request request = new Request.Builder().url(url).build();
        try {
            res = getInstance().syncDeliverResultForString(request);
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
        }
        return res;
    }

    /**
     * 同步get请求返回Map
     * @param url
     * @return
     */
    public static Map<String,String> syncGetForMap(String url){
        Map<String,String> resMap = null;
        Request request = new Request.Builder().url(url).build();
        try {
            resMap = getInstance().syncDeliverResultForMap(request);
        } catch (IOException e) {
            Log.e(TAG,e.getMessage());
        }
        return resMap;
    }

    /**
     * http请求回调类,回调方法在UI线程中执行
     *
     * @param <T>
     */
    public static abstract class ResultCallback<T> {

        Type mType;

        public ResultCallback() {
            mType = getSuperclassTypeParameter(getClass());
        }

        static Type getSuperclassTypeParameter(Class<?> subclass) {
            Type superclass = subclass.getGenericSuperclass();//返回父类的类型
            if (superclass instanceof Class) {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }

        /**
         * 请求成功回调
         *
         * @param response
         */
        public abstract void onSuccess(T response);

        /**
         * 请求失败回调
         *
         * @param e
         */
        public abstract void onFailure(Exception e);
    }

    /**
     * post请求参数类
     */
    public static class Param {

        String key;//请求的参数
        String value;//参数的值

        public Param() {
        }

        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }

    }
}
